C语言走迷宫源代码

C语言走迷宫源代码

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main()
{
  char a[50][50]={"######",
                  "#O #  ",
                  "# ## #",
                  "#  # #",
                  "##   #",
                  "######",
                 };
  int i,x,y,p,q;
  char ch;

  x=1; y=1; p=1; q=5;
  for(i=0;i<=5;i++)
     puts(a[i]);
  while(x!=p || y!=q)
  {
      ch=getch();
    if(ch=='s')
    {
            if(a[x+1][y]!='#')
        {
                  a[x][y]=' ';
            x++;
            a[x][y]='O';
        }
    }
    
    if(ch=='w')
    {
            if(a[x-1][y]!='#')
        {
                  a[x][y]=' ';
            x--;
            a[x][y]='O';
        }
    }
    
    if(ch=='a')
    {
            if(a[x][y-1]!='#')
        {
                  a[x][y]=' ';
            y--;
            a[x][y]='O';
        }
    }
    
    if(ch=='d')
    {
            if(a[x][y+1]!='#')
        {
                  a[x][y]=' ';
            y++;
            a[x][y]='O';
        }
    }
    system("cls");
    for(i=0;i<=5;i++)
        puts(a[i]);
  }
  system("cls");
  printf("You win!\n");
  Sleep(5000);
  return 0;
}

C语言中,编写一个简单的走迷宫游戏的源代码通常会涉及二维数组来表示迷宫,以及路径跟踪算法。Euler's Algorithm (欧拉法) 或者 Depth First Search (深度优先搜索) 可能用于解决这个问题。这里是一个基本的示例,展示如何使用C语言来创建一个控制台版的迷宫游戏: ```c #include <stdio.h> #include <stdlib.h> #define ROWS 5 // 迷宫大小 #define COLS 8 // 定义迷宫地图 char maze[ROWS][COLS] = { {'0', '0', '1', '0', '1', '0', '0', '0'}, // 示例迷宫 {'0', '0', '0', '0', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0', '0', '0', '0'}, {'1', '0', '0', '1', '0', '0', '0', '0'}, {'1', '0', '0', '0', '0', '0', '1', '1'} }; // 检查当前位置是否为空地 int is_empty(int row, int col) { return maze[row][col] == '0'; } // 从起点开始走迷宫 void explore(int start_row, int start_col, int visited[][COLS]) { int current_row = start_row; int current_col = start_col; while (!is_empty(current_row, current_col)) { printf("(%d,%d)", current_row, current_col); // 打印路径 if (current_col > 0 && maze[current_row][current_col - 1] == '0') { // 向左 current_col--; } else if (current_col + 1 < COLS && maze[current_row][current_col + 1] == '0') { // 向右 current_col++; } else if (current_row + 1 < ROWS && maze[current_row + 1][current_col] == '0') { // 向下 current_row++; } else if (current_row - 1 >= 0 && maze[current_row - 1][current_col] == '0') { // 向上 current_row--; } } } int main() { int visited[ROWS][COLS] = {{0}}; // 初始化访问数组 explore(0, 0, visited); // 从起点(0,0)开始探索 return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值